from pg_database import *
from flask import Flask, g
from flask import abort
from flask import request
from flask import Blueprint, current_app
from utils import get_real_addr
from collections import defaultdict
from datetime import timedelta
import json
LOG = config.getlogger()
heartbeat = Blueprint('heartbeat', __name__)

delta = timedelta(hours=8)


@heartbeat.route('/', methods=['GET'])
@heartbeat.route('/<source>', methods=['GET'])
@heartbeat.route('/<source>/<state>', methods=['GET'])
def heartbeat_status(source=None, state=None):
    addr = request.args.get('addr', get_real_addr())
    try:
        query_result = pg_db_session.query(commonheartbeatview)
        query_result = query_result.filter(commonheartbeatview.ip == addr)
        if source:
            query_result = query_result.filter(
                commonheartbeatview.source == source)
        if state:
            query_result = query_result.filter(
                commonheartbeatview.state == state)
        result = defaultdict(dict)
        for i in query_result.all():
            dt = i.contact + delta
            d = dict({'contact': dt.strftime('%Y%m%d%H%M%S')})
            if source and state:
                result = d
            elif source and not state:
                result[i.state] = d
            elif not source and not state:
                result[i.source][i.state] = d
        return json.dumps(result)
    except Exception, ex:
        LOG.error('error: %s', str(ex))
        abort(500)


@heartbeat.route('/<source>', methods=['POST'])
def do_heartbeat(source):
    addr = get_real_addr()
    state = request.form.get('state', '')
    try:
        query_result = pg_db_session.query(commonheartbeatview).filter(
            commonheartbeatview.ip == addr).filter(
                commonheartbeatview.source == source).filter(
                    commonheartbeatview.state == state)
        if query_result.count() == 0:
            pg_db_session.add(commonheartbeat(
                ip=addr, source=source, state=state))
        else:
            query_result.first().contact = int(time.time())
        pg_db_session.commit()
        return 'created'
    except Exception, ex:
        pg_db_session.rollback()
        LOG.error('error: %s', str(ex))
        abort(500)
